// import CryptoJS from '@/common/crypto-js.js'
import md5 from '@/common/md5.min.js'
import base from '@/api/baseUrl.js'
let utils = {
  //H5 剪贴板补充
  setClipboardData: function (text = '', success = '复制成功') {
    // #ifdef H5
    let textarea = document.createElement('textarea')
    textarea.value = text
    textarea.readOnly = 'readOnly'
    document.body.appendChild(textarea)
    textarea.select()
    textarea.setSelectionRange(0, text.length)
    uni.showToast({
      title: success,
      icon: 'success'
    })
    document.execCommand('copy')
    textarea.remove()
    // #endif

    // #ifndef H5
    uni.getClipboardData({
      data: text,
      success: function (res) {
        uni.showToast({
          title: success,
          icon: 'success'
        })
      }
    })
    // #endif
  },

  //获取随机的key
  getRandomKey: function () {
    return Date.now() + Math.floor(Math.random() * 10) + ''
  },
  //打开群组列表
  toGroundList() {
    //html5 A[IM]
    var anchor = document.createElement('a')
    anchor.href = `android://appshell/grouplist`
    anchor.style.display = 'none'
    document.body.appendChild(anchor)
    setTimeout(function () {
      anchor.click()
      document.body.removeChild(anchor)
    }, 66)
  },

  // CryptoJS加密
  encrypt: function (word, keyStr, ivStr) {
    var KEY = CryptoJS.enc.Utf8.parse('yxkj123456123456')
    var IV = CryptoJS.enc.Utf8.parse('yxkj123456123456')

    var key = KEY
    var iv = IV

    if (keyStr) {
      key = CryptoJS.enc.Utf8.parse(keyStr)
      iv = CryptoJS.enc.Utf8.parse(ivStr)
    }

    var srcs = CryptoJS.enc.Utf8.parse(word)
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    })
    return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
  },
  decrypt: function (word, keyStr, ivStr) {
    // 解密
    var key = CryptoJS.enc.Utf8.parse('yxkj123456123456')
    var iv = CryptoJS.enc.Utf8.parse('yxkj123456123456')
    if (keyStr) {
      key = CryptoJS.enc.Utf8.parse(keyStr)
      iv = CryptoJS.enc.Utf8.parse(ivStr)
    }
    var base64 = CryptoJS.enc.Base64.parse(word)
    var src = CryptoJS.enc.Base64.stringify(base64)

    var decrypt = CryptoJS.AES.decrypt(src, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    })
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
    return decryptedStr.toString()
  },
  //延迟返回上级
  delayBack: function () {
    uni.navigateBack(-1)
  },

  //返回上级
  back() {
    // #ifdef H5
    history.back()
    // #endif
    // #ifndef  H5
    uni.navigateBack()
    //#endif
  },

  /*获取当前页url*/
  getCurrentPageUrl: function () {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    return url
  },

  /*获取当前页带参数的url*/
  getCurrentPageUrlWithArgs: function () {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    //拼接url的参数
    var urlWithArgs = url + '?'
    for (var key in options) {
      var value = options[key]
      urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs
  },
  getNowDate: function () {
    const timeOne = new Date()
    const year = timeOne.getFullYear()
    let month = timeOne.getMonth() + 1
    let day = timeOne.getDate()
    month = month < 10 ? '0' + month : month
    day = day < 10 ? '0' + day : day
    const NOW_MONTHS_AGO = `${year}-${month}-${day}`
    return NOW_MONTHS_AGO
  },

  //将某个时间转换成某月某日星期几的格式
  formatDate(time, type) {
    var date = new Date(time)
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = (date.getMinutes() + '').length == 1 ? '0' + date.getMinutes() : date.getMinutes()
    var second = date.getSeconds()
    var week = ''
    switch (date.getDay()) {
      case 0:
        week = '星期天'
        break
      case 1:
        week = '星期一'
        break
      case 2:
        week = '星期二'
        break
      case 3:
        week = '星期三'
        break
      case 4:
        week = '星期四'
        break
      case 5:
        week = '星期五'
        break
      case 6:
        week = '星期六'
        break
    }
    if (!type) return month + '月' + day + '日 ' + week
    else if (type == 'time') return month + '月' + day + '日 ' + hour + ':' + minute
  },

  // ios兼容时间
  createTime: function (key, dtime) {
    function conver(s) {
      return s < 10 ? '0' + s : s
    }
    var myDate = ''
    if (dtime) {
      var str = dtime.replace('T', ' ').replace(new RegExp('-', 'g'), '/')
      if (str.indexOf('.') == '-1') {
        dtime = str
      } else {
        dtime = str.substring(0, str.indexOf('.'))
      }
    }

    var t = Date.parse(dtime)

    if (!isNaN(t)) {
      myDate = new Date(+new Date(dtime))
    } else {
      myDate = new Date()
    }

    var year = myDate.getFullYear()

    var month = myDate.getMonth() + 1

    //获取当前日

    var date = myDate.getDate()

    var h = myDate.getHours() //获取当前小时数(0-23)

    var m = myDate.getMinutes() //获取当前分钟数(0-59)

    var s = myDate.getSeconds()

    var week = myDate.getDay()

    var weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

    if (key == 'yyyy') {
      return year
    } else if (key == 'yyyy-MM') {
      return year + '-' + conver(month)
    } else if (key == 'MM') {
      return conver(month)
    } else if (key == 'dd') {
      return conver(date)
    } else if (key == 'yyyy/MM') {
      return year + '/' + conver(month)
    } else if (key == 'yyyy.MM') {
      return year + '.' + conver(month)
    } else if (key == 'MM-dd') {
      return conver(month) + '-' + conver(date)
    } else if (key == 'MM/dd') {
      return conver(month) + '/' + conver(date)
    } else if (key == 'MM.dd') {
      return conver(month) + '.' + conver(date)
    } else if (key == 'yyyy-MM-dd') {
      return year + '-' + conver(month) + '-' + conver(date)
    } else if (key == 'yyyy/MM/dd') {
      return year + '/' + conver(month) + '/' + conver(date)
    } else if (key == 'yyyy.MM.dd') {
      return year + '.' + conver(month) + '.' + conver(date)
    } else if (key == 'yyyy-MM-dd hh') {
      return year + '-' + conver(month) + '-' + conver(date) + ' ' + conver(h)
    } else if (key == 'yyyy/MM/dd hh') {
      return year + '/' + conver(month) + '/' + conver(date) + ' ' + conver(h)
    } else if (key == 'yyyy.MM.dd hh') {
      return year + '.' + conver(month) + '.' + conver(date) + ' ' + conver(h)
    } else if (key == 'yyyy-MM-dd hh:mm') {
      return year + '-' + conver(month) + '-' + conver(date) + ' ' + conver(h) + ':' + conver(m)
    } else if (key == 'yyyy/MM/dd hh:mm') {
      return year + '/' + conver(month) + '/' + conver(date) + ' ' + conver(h) + ':' + conver(m)
    } else if (key == 'yyyy.MM.dd hh:mm') {
      return year + '.' + conver(month) + '.' + conver(date) + ' ' + conver(h) + ':' + conver(m)
    } else if (key == 'yyyy-MM-dd hh:mm:ss') {
      return (
        year +
        '-' +
        conver(month) +
        '-' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s)
      )
    } else if (key == 'yyyy/MM/dd hh:mm:ss') {
      return (
        year +
        '/' +
        conver(month) +
        '/' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s)
      )
    } else if (key == 'yyyy.MM.dd hh:mm:ss') {
      return (
        year +
        '.' +
        conver(month) +
        '.' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s)
      )
    } else if (key == 'hh:mm:ss') {
      return conver(h) + ':' + conver(m) + ':' + conver(s)
    } else if (key == 'hh:mm') {
      return conver(h) + ':' + conver(m)
    } else if (key == 'yyyy-MM-dd hh:mm:ssT') {
      return (
        year +
        '-' +
        conver(month) +
        '-' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s) +
        ' ' +
        weeks[week]
      )
    } else if (key == 'yyyy/MM/dd hh:mm:ssT') {
      return (
        year +
        '/' +
        conver(month) +
        '/' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s) +
        ' ' +
        weeks[week]
      )
    } else if (key == 'yyyy-MM-dd hh:mm:ssT') {
      return (
        year +
        '.' +
        conver(month) +
        '.' +
        conver(date) +
        ' ' +
        conver(h) +
        ':' +
        conver(m) +
        ':' +
        conver(s) +
        ' ' +
        weeks[week]
      )
    } else if (key == 'yyyy年MM月dd日') {
      return year + '年' + conver(month) + '月' + conver(date) + '日'
    } else if (key == 'yyyy年MM月dd日 hh时mm分ss秒') {
      return (
        year +
        '年' +
        conver(month) +
        '月' +
        conver(date) +
        '日' +
        ' ' +
        conver(h) +
        '时' +
        conver(m) +
        '分' +
        conver(s) +
        '秒'
      )
    } else if (key == 'yyyy年MM月dd日 hh时mm分ss秒T') {
      return (
        year +
        '年' +
        conver(month) +
        '月' +
        conver(date) +
        '日' +
        ' ' +
        conver(h) +
        '时' +
        conver(m) +
        '分' +
        conver(s) +
        '秒' +
        ' ' +
        weeks[week]
      )
    } else if (key == 'MM月dd日 hh时mm分') {
      return conver(month) + '月' + conver(date) + '日' + ' ' + conver(h) + '时' + conver(m) + '分'
    } else if (key == 'MM月dd日 hh:mm') {
      return conver(month) + '月' + conver(date) + '日' + ' ' + conver(h) + ':' + conver(m)
    } else if (key == 'T') {
      return weeks[week]
    } else {
      return year + '-' + conver(month) + '-' + conver(date)
    }
  },

  getSign(val) {
    let sign = md5(val).toLowerCase()
    return sign
  },

  toChinesNum: function (num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'] //changeNum[0] = "零"
    let unit = ['', '十', '百', '千', '万']
    num = parseInt(num)
    let getWan = (temp) => {
      let strArr = temp.toString().split('').reverse()
      let newNum = ''
      for (var i = 0; i < strArr.length; i++) {
        newNum =
          (i == 0 && strArr[i] == 0
            ? ''
            : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
            ? ''
            : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) + newNum
      }
      return newNum
    }
    let overWan = Math.floor(num / 10000)
    let noWan = num % 10000
    if (noWan.toString().length < 4) noWan = '0' + noWan
    return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
  },

  // 打电话
  toCall: function (number) {
    if (!number) {
      return
    }

    try {
      api.callPhone(number)
    } catch (e) {
     
    }
  },
  toCallH5(number){
	  uni.makePhoneCall({
	    phoneNumber: number
	  })
  },
  getArr(img) {
    var list = img.split(',')
    var imgString = list.length > 0 ? list[0] : ''
    return imgString
  },
  // 打开即时通讯
  toMsg: function (number) {
    if (!number) {
      return
    }
    //html5 A[IM]
    var anchor = document.createElement('a')
    anchor.href = `android://appshell/chat?conversationId=${number}`
    anchor.style.display = 'none'
    document.body.appendChild(anchor)
    setTimeout(function () {
      anchor.click()
      document.body.removeChild(anchor)
    }, 66)
  },
  
  //获取 图片
  getPic: function (attachmentID) {
    let url =
      base.uploadFileImgUrl +'/stationery?attachmentId=' + attachmentID
    return url
  },
  getPrant(urls){
	  console.log('getPrant',url)
	if(url == ''){
	  return
	}
	var url = []
	url.push(urls)
  	uni.previewImage({
  		urls:url,
  		current:0,
  		longPressActions: {
  			success: function(data) {},
  			fail: function(err) {
  			}
  		}
  	});
  },
  // 预览
  previewImageList(image,index){
  	 console.log("image",image,index)
    var imgString = [];
    if(image.length>0){
  	 imgString = image.map(item => utils.getPic(item))
    }else{
  	  imgString = [];
    }
    uni.previewImage({
  	urls:imgString,
  	current:index,
  	longPressActions: {
  		success: function(data) {},
  		fail: function(err) {
  		}
  	}
  	});
  },
  
  //获取颜色
  getColor(religiousCategory) {
    var typeNum =
      religiousCategory == '佛教'
        ? 0
        : religiousCategory == '道教'
        ? 1
        : religiousCategory == '伊斯兰教'
        ? 2
        : religiousCategory == '天主教'
        ? 3
        : religiousCategory == '基督教'
        ? 4
        : religiousCategory == '民间信仰'
        ? 5
        : religiousCategory == '其他'
        ? 6
        : religiousCategory == '以堂带点'
		? 7
		:''
    return typeNum
  },
	bd_encrypta(gg_lon, gg_lat) {
	  var X_PI = Math.PI * 3000.0 / 180.0;
	  var x = gg_lon, y = gg_lat;
	  var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
	  var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
	  var bd_lon = z * Math.cos(theta) + 0.0065;
	  var bd_lat = z * Math.sin(theta) + 0.006;
	  return [bd_lon, bd_lat]
	},
  getColorStyle(religiousCategory) {
    var typeNum =
      religiousCategory == '佛教'
        ? '#E3AC07'
        : religiousCategory == '道教'
        ? '#3576D3'
        : religiousCategory == '伊斯兰教'
        ? '#2BA656'
        : religiousCategory == '天主教'
        ? '#DB4664'
        : religiousCategory == '基督教'
        ? '#1FC6D1'
        : religiousCategory == '民间信仰'
        ? '#E56F15'
        : religiousCategory == '其他'
        ? '#1BB1FD'
        : ''
    return typeNum
  },
  //加法计算
  jia(num1, num2) {
    if (!num1) {
      num1 = 0
    }
    if (!num2) {
      num2 = 0
    }
    return new Decimal(num1).add(new Decimal(num2)).toNumber()
  },
  //减法计算
  jian(num1, num2) {
    if (!num1) {
      num1 = 0
    }
    if (!num2) {
      num2 = 0
    }
    return new Decimal(num1).sub(new Decimal(num2)).toNumber()
  },
  //乘
  cheng(num1, num2) {
    if (!num1) {
      num1 = 0
    }
    if (!num2) {
      num2 = 0
    }
    return new Decimal(num1).mul(new Decimal(num2)).toNumber()
  },
  //除
  chu(num1, num2) {
    if (!num1) {
      num1 = 0
    }
    if (!num2) {
      num2 = 0
    }
    return new Decimal(num1).div(new Decimal(num2)).toNumber()
  },
  //数组转字符串
  getString(val, type) {
    if (val == [] || val == null) {
      return ''
    }
    const string = val.join(type)
    return string
  },
  //字符串转数组
  getArray(val, type) {
    if (val == '' || val == null) {
      return []
    }
    const array = val.split(type)
    return array
  },
  //获取过去年份
  getCurrentYear(type) {
    var nowData = new Date().getFullYear()
    const pastYears = []
    if (type == 1) {
      //不带全部
      for (let i = 0; i < 7; i++) {
        pastYears.push(nowData - i + '年度')
      }
    }
    if (type == 2) {
      //带全部
      for (let i = 0; i < 7; i++) {
        pastYears.push({
          id: nowData - i,
          name: nowData - i + '年度'
        })
      }
      pastYears.unshift({
        id: 4,
        name: '全部'
      })
    }
    if (type == 3) {
      for (let i = 0; i < 7; i++) {
        pastYears.push({
          id: nowData - i,
          name: nowData - i + '年度'
        })
      }
    }
    return pastYears
  },
  getLocations(options) {
    return new Promise((resolve, reject) => {
  	  jWeixin.config({
		  beta: true,// 调用wx.invoke形式的接口值时，该值必须为true。
		  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		  appId: options.appId, // 必填，山东通的cropID
		  timestamp: options.timestamp, // 必填，生成签名的时间戳
		  nonceStr: options.nonceStr, // 必填，生成签名的随机串
		  signature: options.signature,// 必填，签名，见附录1
		  jsApiList: ["getLocation"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		});
  		jWeixin.ready(function(){
  			// config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
  			jWeixin.getLocation({
  			  type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
  			  success: (res) => resolve(res),
  			  fail: (err) => reject(err)
  			});
  		  });
    });
  }
}

export default utils
